package com.imooc.controller.intercept;

import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 拦截器
 * @author Zhou
 * @create 2020-11-25 21:43
 */
public class MiniInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisOperator redis;

    public static final String USER_REDIS_SESSION = "user_redis_session";
    /**
     * 拦截请求，调用controller之前
     * @param request
     * @param response
     * @param o
     * @return false：请求被拦截返回。true：请求通过，可以继续执行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String userId = request.getHeader("userId");
        String userToken = request.getHeader("userToken");

        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userToken)){//表示没有登录
            System.out.println("请登录");
            returnErrorResponse(response, IMoocJSONResult.errorTokenMsg("请登录"));
            return false;
        }else {
            String uniqueToken = redis.get(USER_REDIS_SESSION + ":" + userId);
            if (StringUtils.isEmpty(uniqueToken)){//有可能用户的时间失效，那么前端穿过来是有值的。但查询到的是空
                System.out.println("请登录");
                returnErrorResponse(response, IMoocJSONResult.errorTokenMsg("请登录"));
                return false;
            }else {
                if (! uniqueToken.equals(userToken)){
                    System.out.println("账号被挤出");
                    returnErrorResponse(response, IMoocJSONResult.errorTokenMsg("账号在别的手机端登录"));
                    return false;
                }
            }

            System.out.println("进行了拦截");
            return true;
        }
    }

    /**
     * 将一个Json对象转化为byte数组进行输出
     * @param response
     * @param result
     * @throws IOException
     */
    public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException {
        OutputStream os = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            os = response.getOutputStream();
            os.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null){
                os.close();
            }
        }
    }
    /**
     * 请求Controller之后，渲染视图之前
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求controller之后，渲染视图之前
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
